/*
* Copyright (c) 2024 -present FengJinjian ( 751965763@qq.com )

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package edu.vital.energy.longevity.controller;

import edu.vital.energy.longevity.common.ApiResponse;
import edu.vital.energy.longevity.domain.dto.contract.ContractCreateDTO;
import edu.vital.energy.longevity.domain.dto.contract.ContractQueryDTO;
import edu.vital.energy.longevity.domain.dto.contract.ContractUpdateDTO;
import edu.vital.energy.longevity.service.IContractService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合同表控制器
 * 提供合同表的CRUD、导入导出、状态管理等功能
 *
 * @version 1.0.1
 * @author Feng JinJian
 * @date 2025-01-14
 */
@Slf4j
@Tag(name = "合同表", description = "合同表相关接口")
@RestController
@RequestMapping("/api/contract")
public class ContractController {

    @Autowired
    private IContractService contractService;

    @Operation(summary = "分页查询合同表列表", description = "支持按合同表编号、名称、状态等条件筛选")
    @GetMapping("/page")
    public ResponseEntity<?> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "查询条件") ContractQueryDTO query) {
        log.info("分页查询合同表列表: pageNum={}, pageSize={}, query={}", pageNum, pageSize, query);
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("data", contractService.getContractPage(pageNum, pageSize, query));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return handleError(e);
        }
    }

    @Operation(summary = "获取合同表详情", description = "根据合同表ID查询详细信息")
    @GetMapping("/{id}")
    public ResponseEntity<?> getById(
            @Parameter(description = "合同表ID") @PathVariable Long id) {
        log.info("查询合同表详情: id={}", id);
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("data", contractService.getContractById(id));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return handleError(e);
        }
    }

    @Operation(summary = "新增合同表", description = "创建新的合同表记录")
    @PostMapping
    public ResponseEntity<ApiResponse<ApiResponse>> create(
            @Parameter(description = "合同表信息") @RequestBody @Valid ContractCreateDTO dto) {
        log.info("创建合同表: {}", dto);
        try {
            Long id = contractService.createContract(dto);
            return ResponseEntity.ok(new ApiResponse<ApiResponse>(0,"SUCCESS", "创建成功", ApiResponse.success(id)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(1,"ERROR", e.getMessage(), null));
        }
    }

    @Operation(summary = "修改合同表", description = "更新已有合同表信息")
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Integer>> update(
            @Parameter(description = "合同表ID") @PathVariable Long id,
            @Parameter(description = "更新信息") @RequestBody @Valid ContractUpdateDTO dto) {
        log.info("修改合同表: id={}, dto={}", id, dto);
        try {
            int rows = contractService.updateContract(id, dto);
            return ResponseEntity.ok(new ApiResponse<>(0,"SUCCESS","更新成功", rows));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(1,"ERROR", e.getMessage(), null));
        }
    }

    @Operation(summary = "删除合同表", description = "根据ID删除合同表")
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Integer>> delete(
            @Parameter(description = "合同表ID") @PathVariable Long id) {
        log.info("删除合同表: id={}", id);
        try {
            int rows = contractService.deleteContract(id);
            return ResponseEntity.ok(new ApiResponse<>(0,"SUCCESS", "删除成功", rows));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(1,"ERROR", e.getMessage(), null));
        }
    }

    @Operation(summary = "批量删除合同表", description = "根据ID列表批量删除合同表")
    @DeleteMapping("/batch")
    public ResponseEntity<ApiResponse<Integer>> batchDelete(
            @Parameter(description = "合同表ID列表") @RequestBody List<Long> ids) {
        log.info("批量删除合同表: ids={}", ids);
        try {
            int rows = contractService.batchDeleteContract(ids);
            return ResponseEntity.ok(new ApiResponse<>(0,"SUCCESS", "批量删除成功", rows));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(1,"ERROR", e.getMessage(), null));
        }
    }

    @Operation(summary = "导出合同表", description = "根据查询条件导出合同表数据")
    @GetMapping("/export")
    public ResponseEntity<?> export(
            @Parameter(description = "查询条件") ContractQueryDTO query) {
        log.info("导出合同表数据: query={}", query);
        try {
            byte[] data = contractService.exportContract(query);
            return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=contracts.xlsx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(data);
        } catch (Exception e) {
            return handleError(e);
        }
    }

    @Operation(summary = "导入合同表", description = "从Excel文件导入合同表数据")
    @PostMapping("/import")
    public ResponseEntity<?> importData(
            @Parameter(description = "Excel文件") @RequestParam("file") MultipartFile file) {
        log.info("导入合同表数据: fileName={}", file.getOriginalFilename());
        try {
            contractService.importContract(file);
            return ResponseEntity.ok(Map.of("code", 0, "data", null));
        } catch (Exception e) {
            return handleError(e);
        }
    }

    @Operation(summary = "更新合同表状态", description = "变更合同表状态（如：草稿、审核中、已生效等）")
    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateStatus(
            @Parameter(description = "合同表ID") @PathVariable Long id,
            @Parameter(description = "状态值") @RequestParam Integer status) {
        log.info("更新合同表状态: id={}, status={}", id, status);
        try {
            contractService.updateContractStatus(id, status);
            return ResponseEntity.ok(Map.of("code", 0, "data", null));
        } catch (Exception e) {
            return handleError(e);
        }
    }

    private <T> ResponseEntity<ApiResponse<T>> handleError(Exception e) {
        log.error("合同表操作异常", e);
        return ResponseEntity.badRequest().body(new ApiResponse<>(1,"ERROR", e.getMessage(), null));
    }
}
